﻿using DDNS.Cache;
using DDNS.Infrastructure;
using DDNS.Model.Config;
using DDNS.Model.Entities;
using DDNS.Model.Enum;
using DDNS.Model.Results;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace DDNS_IPv4_IPv6.API
{
    /// <summary>
    /// API主入口
    /// </summary>
    public static class MainApi
    {
        /// <summary>
        /// 缓存配置数据
        /// </summary>
        private static CachesConfig _cacheConfig;

        /// <summary>
        /// 针对DDNS的API处理   JsonConvert.SerializeObject(对象/对象列表);
        /// </summary>
        /// <param name="app"></param>
        public static void ApiHelpser(WebApplication app)
        {
            _cacheConfig = PassportConfig.Get<CachesConfig>("Caches") ?? throw new ArgumentNullException("Caches config is null");//获取配置信息

            app.MapPost("/SetDomain", ([FromForm] List<DomainName> list, ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    List<DomainName> listDto = new List<DomainName>();
                    foreach (var item in list)
                    {
                        var isbool = Tools.IsDomain(item.Domain);
                        if (isbool)
                        {
                            listDto.Add(item);
                        }
                    }//正则判断过滤掉不是域名的数据
                    if (listDto.Count <= 0)
                    {
                        _log4Net.LogWarning($"传入的所有域名[{string.Join(",", list.Select(m => m.Domain).ToArray())}]都不是正确的域名，请检查重新输入");
                        ret = new ApiResult<object>()
                        {
                            Code = EnumStatus.Fail,
                            Message = $"传入的所有域名[{string.Join(",", list.Select(m => m.Domain).ToArray())}]都不是正确的域名，请检查重新输入"
                        };
                        return ret;
                    }
                    var domainList = CacheHelper.GetCache<List<DomainName>>(_cacheConfig.DomainKey);

                    if (domainList?.Count > 0)
                    {
                        var existList = domainList.Where(m => listDto.Select(g => g.Domain).Contains(m.Domain)).ToList();//获取传入的数据中有多少是已存在的数据
                        if (existList?.Count > 0)
                        {
                            foreach (var item in domainList)
                            {
                                foreach (var temp in listDto)
                                {
                                    if (item.Domain == temp.Domain)
                                    {
                                        item.Type = temp.Type;
                                    }//缓存中存在该域名则更新域名类型
                                }
                            }
                            //添加不存在缓存的数据
                            var templist = listDto.Where(m => !existList.Select(g => g.Domain).Contains(m.Domain)).ToList();
                            foreach (var item in templist) { domainList.Add(item); }
                        }
                        else
                        {
                            foreach (var item in listDto) { domainList.Add(item); }//增量添加出入的域名数据
                        }
                    }//缓存不为空，则增添添加域名到缓存中（缓存中有当前域名的更改域名解析类型）
                    else
                    {
                        domainList = new List<DomainName>();
                        foreach (var item in listDto) { domainList.Add(item); }
                    }//缓存为空，则添加当前设置的域名到缓存
                    CacheHelper.SetCache(_cacheConfig.DomainKey, domainList, DateTime.Now.AddYears(1));
                    CacheHelper.SetCache<string>(_cacheConfig.IsUpdateIPv4Key, "true", DateTime.Now.AddYears(1));//更新IPv4列表标记
                    CacheHelper.SetCache<string>(_cacheConfig.IsUpdateIPv6Key, "true", DateTime.Now.AddYears(1));//更新IPv6列表标记
                    ret = new ApiResult<object>() { Code = EnumStatus.Success, Message = "保存成功" };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"保存域名异常：{ex.Message}");
                    ret = new ApiResult<object>() { Code = EnumStatus.Fail, Message = "保存异常", Data = ex.Message };
                }
                return ret;
            }).WithTags("1、添加需要动态解析的域名");

            app.MapDelete("/DelAll", (ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    CacheHelper.RemoveCache(_cacheConfig.DomainKey);
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Success,
                        Message = "删除成功"
                    };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"删除所有需要动态解析的域名异常：{ex.Message}");
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Fail,
                        Message = "删除异常"
                    };
                }
                return ret;
            }).WithTags("2、删除所有需要动态解析的域名");

            app.MapDelete("/DelDomain", ([FromQuery] string domain, ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    var domainList = CacheHelper.GetCache<List<DomainName>>(_cacheConfig.DomainKey);
                    if (domainList?.Count > 0)
                    {
                        int suo = 0;
                        List<DomainName> templist = new List<DomainName>();
                        foreach (var item in domainList)
                        {
                            if (item.Domain == domain)
                            {
                                suo++;
                            }
                            else
                            {
                                templist.Add(item);
                            }
                        }
                        if (suo > 0)
                        {
                            CacheHelper.SetCache(_cacheConfig.DomainKey, templist, DateTime.Now.AddYears(1));
                        }
                    }
                    ret = new ApiResult<object>() { Code = EnumStatus.Success, Message = "删除成功" };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"删除指定需要动态解析的域名异常：{ex.Message}");
                    ret = new ApiResult<object>() { Code = EnumStatus.Fail, Message = "删除异常", Data = ex.Message };
                }
                return ret;
            }).WithTags("2、删除指定需要动态解析的域名");

            app.MapGet("/GetAllDomain", ( ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    var domainList = CacheHelper.GetCache<List<DomainName>>(_cacheConfig.DomainKey);
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Success,
                        Message = "获取成功",
                        Data = domainList
                    };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"获取所有需要动态解析的域名异常：{ex.Message}");
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Fail,
                        Message = "获取所有需要动态解析的域名异常",
                    };
                }
                return ret;
            }).WithTags("3、获取所有需要动态解析的域名");

            app.MapGet("/GetDomain_IPv4", (ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    var domainList = CacheHelper.GetCache<List<DomainName>>(_cacheConfig.DomainKey);
                    if (domainList == null)
                    {
                        var retNull = new ApiResult<object>()
                        {
                            Code = EnumStatus.Fail,
                            Message = "当前还没有保存到需要进行IPv4动态解析的域名",
                            Data = domainList
                        };
                        return retNull;
                    }
                    domainList = domainList.Where(m => m.Type == EnumDomainType.IPv4 || m.Type == EnumDomainType.ALL).ToList();
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Success,
                        Message = "获取成功",
                        Data = domainList
                    };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"获取所有需要IPv4动态解析的域名异常：{ex.Message}");
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Fail,
                        Message = "获取所有需要IPv4动态解析的域名异常"
                    };
                }
                return ret;
            }).WithTags("3、获取所有需要IPv4动态解析的域名");

            app.MapGet("/GetDomain_IPv6", (ILogger<Program> _log4Net) =>
            {
                ApiResult<object> ret = new ApiResult<object>();
                try
                {
                    var domainList = CacheHelper.GetCache<List<DomainName>>(_cacheConfig.DomainKey);
                    if (domainList == null)
                    {
                        var retNull = new ApiResult<object>()
                        {
                            Code = EnumStatus.Success,
                            Message = "当前还没有保存到需要进行IPv6动态解析的域名",
                            Data = domainList
                        };
                        return retNull;
                    }
                    domainList = domainList.Where(m => m.Type == EnumDomainType.IPv6 || m.Type == EnumDomainType.ALL).ToList();
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Success,
                        Message = "获取成功",
                        Data = domainList
                    };
                }
                catch (Exception ex)
                {
                    _log4Net.LogError($"获取所有需要IPv6动态解析的域名异常：{ex.Message}");
                    ret = new ApiResult<object>()
                    {
                        Code = EnumStatus.Fail,
                        Message = "获取所有需要IPv6动态解析的域名异常"
                    };
                }
                return ret;
            }).WithTags("3、获取所有需要IPv6动态解析的域名");
        }
    }
}
